// build 20240524
// Accepts input from GPIO
// Dependency Components: dxLogger,dxDriver,dxEventBus
import { gpioKeyClass } from './libvbar-m-dxkey.so'
import bus from './dxEventBus.js'
import * as os from "os";
const gpioKeyObj = new gpioKeyClass();
const gpioKey = {}

/**
 * gpioKey initialization
 * @returns true:success,false:fail
 */
gpioKey.init = function () {
	const res = gpioKeyObj.init()
	if (res) {
		gpioKeyObj.registerCb("gpioKeyCb")
	}
	return res
}

/**
 * gpioKey Cancel initialization
 * @returns true:success,false:fail
 */
gpioKey.deinit = function () {
	gpioKeyObj.unRegisterCb("gpioKeyCb")
	return gpioKeyObj.deinit()
}

/**
 * Check if the gpioKey message queue is empty.
 * @returns true:success,false:fail
 */
gpioKey.msgIsEmpty = function () {
	return gpioKeyObj.msgIsEmpty()
}

/**
 * Read data from the gpioKey message queue
 * @returns JSON message object, format:{"code":30,"type":1,"value":1}
 */
gpioKey.msgReceive = function () {
	let msg = gpioKeyObj.msgReceive()
	return JSON.parse(msg);
}

gpioKey.RECEIVE_MSG = '__gpioKey__MsgReceive'

/**
 * Simplify the use of the gpiokey component; no need to poll for data, data is sent via eventbus.
 * `run` executes only once.
 * If real-time data retrieval is required, subscribe to eventbus events. The event topic is `GPIO_KEY`, and the event content is similar to `{"code":30,"type":1,"value":1}`.
 * The code is the GPIO identifier, indicating which GPIO has input. The value can only be 0; 1 usually represents a low or high level.
 * `type` specifies the event type, following Linux standard input conventions. Here are some commonly used ones:
 	(0x01): Key events, including all keyboard and button events. For example, pressing or releasing a key on the keyboard will report this type of event.
	(0x05): Switch events, such as the opening and closing of a laptop lid, which can report the open/closed state.
	(0x11): LED events, used to control LED indicators on the device.
	(0x12): Sound events, used to control sound output on the device.
	(0x16): Power events, which can be used to report power button events or low battery events.
 * 
 */
gpioKey.run = function () {
	bus.newWorker("__gpiokey", '/app/code/dxmodules/gpioKeyWorker.js')
}

/**
 * If gpioKey is a standalone thread, you can directly use the run function, which will automatically start a thread.
 * If you want to join it to another existing thread, you can use the following wrapper function.
 */
gpioKey.worker = {
	//Before the while loop
	beforeLoop: function () {
		gpioKey.init()
	},
	//In a while loop
	loop: function () {
		if (!gpioKey.msgIsEmpty()) {
			let res = gpioKey.msgReceive();
			bus.fire(gpioKey.RECEIVE_MSG, res)
		}
	}
}
export default gpioKey;
